<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use think\Controller;
use think\Db;
use think\Request;


class Fishinggroundcomments extends Api
{
    private static $model;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\common\model\FishingGroundComments();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function lists()
    {
        $pageSize = input('pagesize', 15);

        $groundId = input('ground_id');
        if (!$groundId) {
            $this->error('参数缺失！');
        }

        $groundInfo = \app\common\model\FishingGround::find($groundId);
        if (!$groundInfo) {
            $this->error('该钓场不存在！');
        }
        $userId = $this->auth->id;
        $where = [
            'status' => 1,
            'user_id' => $userId,
            'ground_id' => $groundId,
        ];

        $list = self::$model->where($where)->order('createtime desc')->paginate($pageSize);
        if ($list) {
            foreach ($list as $val) {
                $val->avatar = \app\common\model\User::where('id', $val->user_id)->value('avatar');
            }
        }

        $this->success('钓场评论列表', $list);
    }

    /**
     * 钓场评论
     */
    public function create()
    {
        $groundId = input('ground_id');
        if (!$groundId) {
            $this->error('参数缺失！');
        }

        $groundInfo = \app\common\model\FishingGround::find($groundId);
        if (!$groundInfo) {
            $this->error('该钓场不存在！');
        }

        if ($groundInfo->source_type != 2) {
            $this->error('该钓场非野钓场！');
        }

        $content = input('content');
        if (!$content) {
            $this->error('请输入评论内容！');
        }

        $star = input('star');
        $pics = input('pics');

        $userId = $this->auth->id;
        $cdata = [
            'user_id' => $userId,
            'content' => $content,
            'ground_id' => $groundId,
            'star' => $star,
            'pics' => $pics,
        ];

        $ret = self::$model->create($cdata);
        if (!$ret) {
            $this->error('评论失败！');
        }

        $totalStars = self::$model->where('ground_id', $groundId)->sum('star');
        $totalNums = self::$model->where('ground_id', $groundId)->count();
        if ($totalNums > 0) {
            $stars = round(($totalStars / $totalNums), 1);
        } else {
            $stars = 0;
        }

        \app\common\model\FishingGround::where('id', $groundId)->update(['star' => $stars]);

        \app\common\model\UserScoreLog::commentBonus($this->auth->id);

        $this->success('评论成功！');
    }
}
